﻿Imports DotNetNuke
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Services.Localization.Localization
Imports System.Web.UI.WebControls
Imports DotNetNuke.Framework
Imports System.Text
Imports System.Xml

Namespace DotNetNuke.Modules.ActiveForums.Controls
    Public Class Settings
        Inherits ForumSettingsBase

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            ServicesFramework.Instance.RequestAjaxAntiForgerySupport()

            txtPageSize.Style.Add("float", "none")
            txtPageSize.EmptyMessageStyle.CssClass += "dnnformHint"
            txtPageSize.NumberFormat.DecimalDigits = 0
            txtPageSize.IncrementSettings.Step = 5


            txtFloodInterval.Style.Add("float", "none")
            txtFloodInterval.EmptyMessageStyle.CssClass += "dnnformHint"
            txtFloodInterval.NumberFormat.DecimalDigits = 0
            txtFloodInterval.IncrementSettings.Step = 30


            txtEditInterval.Style.Add("float", "none")
            txtEditInterval.EmptyMessageStyle.CssClass += "dnnformHint"
            txtEditInterval.NumberFormat.DecimalDigits = 0
            txtEditInterval.IncrementSettings.Step = 1


            If Not Utilities.IsRewriteLoaded() Or PortalSettings.PortalAlias.HTTPAlias.ToString.Contains("/") Then
                rdEnableURLRewriter.SelectedIndex = 1
                rdEnableURLRewriter.Enabled = False
                rdEnableURLRewriter.Enabled = False
            End If
            Dim u As DotNetNuke.Entities.Users.UserInfo = DotNetNuke.Entities.Users.UserController.GetCurrentUserInfo()

            If u.IsSuperUser And Request.ServerVariables("SERVER_SOFTWARE").Contains("7") And Not PortalSettings.PortalAlias.HTTPAlias.ToString.Contains("/") Then
                If Utilities.IsRewriteLoaded() Then
                    litToggleConfig.Text = "<a href=""javascript:void(0);"" onclick=""amaf_toggleConfig('configdisable',this); return false;"">Uninstall Active Forums URL Handler</a>"
                Else
                    litToggleConfig.Text = "<a href=""javascript:void(0);"" onclick=""amaf_toggleConfig('configenable',this); return false;"">Install Active Forums URL Handler</a>"
                End If

            End If


        End Sub
#Region "Base Method Implementations"

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' LoadSettings loads the settings from the Database and displays them
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Public Overrides Sub LoadSettings()
            Try
                If (Page.IsPostBack = False) Then
                    BindThemes()
                    BindTemplates()
                    BindPrivateMessaging()
                    BindForumGroups()
                    BindForumSecurity()


                    rdFullTextSearch.SelectedIndex = 1
                    rdMailQueue.SelectedIndex = 1
                    rdAutoLinks.SelectedIndex = 0
                    rdPoints.SelectedIndex = 1

                    txtPageSize.Value = 20
                    txtPageSize.Text = "20"
                    txtFloodInterval.Value = 0
                    txtFloodInterval.Text = "0"
                    txtEditInterval.Value = 0
                    txtEditInterval.Text = "0"

                    drpMode.SelectedIndex = drpMode.Items.IndexOf(drpMode.Items.FindByValue(Mode))
                    drpThemes.SelectedIndex = drpThemes.Items.IndexOf(drpThemes.Items.FindByValue(Theme))
                    drpTemplates.SelectedIndex = drpTemplates.Items.IndexOf(drpTemplates.Items.FindByValue(TemplateId.ToString()))
                    txtPageSize.Text = PageSize.ToString()
                    txtFloodInterval.Text = FloodInterval.ToString()
                    txtEditInterval.Text = EditInterval.ToString()
                    rdAutoLinks.SelectedIndex = rdAutoLinks.Items.IndexOf(rdAutoLinks.Items.FindByValue(AutoLink.ToString()))
                    drpDeleteBehavior.SelectedIndex = drpDeleteBehavior.Items.IndexOf(drpDeleteBehavior.Items.FindByValue(DeleteBehavior.ToString()))
                    txtAddThis.Text = AddThis
                    drpProfileType.SelectedIndex = drpProfileType.Items.IndexOf(drpProfileType.Items.FindByValue(ProfileType.ToString()))
                    drpSignatures.SelectedIndex = drpSignatures.Items.IndexOf(drpSignatures.Items.FindByValue(Signatures.ToString()))
                    drpUserDisplayMode.SelectedIndex = drpUserDisplayMode.Items.IndexOf(drpUserDisplayMode.Items.FindByValue(UserNameDisplay))
                    rdEnableURLRewriter.SelectedIndex = rdEnableURLRewriter.Items.IndexOf(rdEnableURLRewriter.Items.FindByValue(FriendlyURLs.ToString()))
                    rdFullTextSearch.SelectedIndex = rdFullTextSearch.Items.IndexOf(rdFullTextSearch.Items.FindByValue(FullTextSearch.ToString()))
                    rdMailQueue.SelectedIndex = rdMailQueue.Items.IndexOf(rdMailQueue.Items.FindByValue(MailQueue.ToString()))

                    rdPoints.SelectedIndex = rdPoints.Items.IndexOf(rdPoints.Items.FindByValue(EnablePoints.ToString()))
                    txtAnswerPointValue.Text = AnswerPointValue.ToString()
                    txtTopicPointValue.Text = TopicPointValue.ToString()
                    txtReplyPointValue.Text = ReplyPointValue.ToString()
                    txtMarkAnswerPointValue.Text = MarkAsAnswerPointValue.ToString()
                    txtModPointValue.Text = ModPointValue.ToString()

                    txtURLPrefixBase.Text = PrefixURLBase
                    txtURLPrefixCategory.Text = PrefixURLCategory
                    txtURLPrefixOther.Text = PrefixURLOther
                    txtURLPrefixTags.Text = PrefixURLTag

                    txtAvatarHeight.Text = AvatarHeight.ToString()
                    txtAvatarWidth.Text = AvatarWidth.ToString()

                    drpForumGroupTemplate.SelectedIndex = drpForumGroupTemplate.Items.IndexOf(drpForumGroupTemplate.Items.FindByValue(ForumGroupTemplate.ToString()))


                End If
            Catch exc As Exception           'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' UpdateSettings saves the modified settings to the Database
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Public Overrides Sub UpdateSettings()
            Try
                Dim fullTextCurrent As Boolean = FullTextSearch


                Theme = drpThemes.SelectedItem.Value
                Mode = drpMode.SelectedItem.Value
                TemplateId = Convert.ToInt32(drpTemplates.SelectedItem.Value)
                PageSize = Convert.ToInt32(txtPageSize.Text)
                FloodInterval = Convert.ToInt32(txtFloodInterval.Text)
                EditInterval = Convert.ToInt32(txtEditInterval.Text)
                AutoLink = Convert.ToBoolean(rdAutoLinks.SelectedItem.Value)
                DeleteBehavior = Convert.ToInt32(drpDeleteBehavior.SelectedItem.Value)
                AddThis = txtAddThis.Text
                ProfileType = Convert.ToInt32(drpProfileType.SelectedItem.Value)
                Signatures = Convert.ToInt32(drpSignatures.SelectedItem.Value)
                UserNameDisplay = drpUserDisplayMode.SelectedItem.Value
                FriendlyURLs = Convert.ToBoolean(rdEnableURLRewriter.SelectedItem.Value)
                FullTextSearch = Convert.ToBoolean(rdFullTextSearch.SelectedItem.Value)
                MailQueue = Convert.ToBoolean(rdMailQueue.SelectedItem.Value)

                PrefixURLBase = txtURLPrefixBase.Text
                PrefixURLCategory = txtURLPrefixCategory.Text
                PrefixURLOther = txtURLPrefixOther.Text
                PrefixURLTag = txtURLPrefixTags.Text

                AnswerPointValue = Convert.ToInt32(txtAnswerPointValue.Text)
                ReplyPointValue = Convert.ToInt32(txtReplyPointValue.Text)
                MarkAsAnswerPointValue = Convert.ToInt32(txtMarkAnswerPointValue.Text)
                TopicPointValue = Convert.ToInt32(txtTopicPointValue.Text)
                ModPointValue = Convert.ToInt32(txtModPointValue.Text)

                AvatarHeight = Convert.ToInt32(txtAvatarHeight.Text)
                AvatarWidth = Convert.ToInt32(txtAvatarWidth.Text)


                ForumGroupTemplate = Convert.ToInt32(drpForumGroupTemplate.SelectedItem.Value)
                Dim adminSec() As String = txtGroupModSec.Value.Split(CChar(","))
                SaveForumSecurity("groupadmin", adminSec)
                Dim memSec() As String = txtGroupMemSec.Value.Split(CChar(","))
                SaveForumSecurity("groupmember", memSec)
                Dim regSec() As String = txtGroupRegSec.Value.Split(CChar(","))
                SaveForumSecurity("registereduser", regSec)
                Dim anonSec() As String = txtGroupAnonSec.Value.Split(CChar(","))
                SaveForumSecurity("anon", anonSec)


                Try
                    If FullTextSearch = True And fullTextCurrent = False Then
                        DataProvider.Instance.Search_ManageFullText(FullTextSearch)
                        Dim err As String = String.Empty
                        Dim s As String = Utilities.GetSqlString("FullText.sql")
                        err = DotNetNuke.Data.DataProvider.Instance().ExecuteScript(s)
                    ElseIf FullTextSearch = False And fullTextCurrent = True Then
                        DataProvider.Instance.Search_ManageFullText(FullTextSearch)
                    End If
                Catch ex As Exception
                    FullTextSearch = False
                    DotNetNuke.Services.Exceptions.ProcessModuleLoadException(Me, ex)
                End Try

            Catch exc As Exception           'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

#End Region
#Region "Private Methods"
        Private Sub BindTemplates()
            Dim tc As New TemplateController
            Dim tl As New List(Of TemplateInfo)
            tl = tc.Template_List(PortalId, ModuleId, Templates.TemplateTypes.ForumView)
            drpTemplates.DataTextField = "Title"
            drpTemplates.DataValueField = "TemplateId"
            drpTemplates.DataSource = tl
            drpTemplates.DataBind()
            drpTemplates.Items.Insert(0, New ListItem(LocalizeString("Default"), "0"))
        End Sub
        Private Sub BindThemes()
            Dim di As New IO.DirectoryInfo(Server.MapPath("~/DesktopModules/ActiveForums/themes"))
            drpThemes.DataSource = di.GetDirectories()
            drpThemes.DataBind()
        End Sub
        Private Sub BindPrivateMessaging()

            Dim mc As New DotNetNuke.Entities.Modules.ModuleController
            Dim tc As New DotNetNuke.Entities.Tabs.TabController
            Dim ti As DotNetNuke.Entities.Tabs.TabInfo = Nothing
            For Each mi As DotNetNuke.Entities.Modules.ModuleInfo In mc.GetModules(PortalId)



                If mi.DesktopModule.ModuleName.Contains("Active Social") And mi.IsDeleted = False Then
                    ti = tc.GetTab(mi.TabID, PortalId, False)
                    If Not ti Is Nothing Then
                        If ti.IsDeleted = False Then
                            drpProfileType.Items.Add(New ListItem(ti.TabName & " - Active Social", "3"))

                        End If
                    End If
                End If
            Next
        End Sub
        Private Sub BindForumGroups()
            Using dr As IDataReader = DataProvider.Instance.Forums_List(PortalId, ModuleId, -1, -1, False)
                Dim dt As New DataTable("Forums")
                Dim row As DataRow = Nothing
                dt.Load(dr)
                dr.Close()




                Dim totalGroupForum As Integer = 0
                Dim tmpGroup As String = String.Empty
                Dim i As Integer = 0
                Dim groupCount As Integer = 0
                Dim forumCount As Integer = 0
                Dim hasChildren As Boolean = False
                For Each row In dt.Rows
                    If tmpGroup <> row("ForumGroupId").ToString() Then
                        drpForumGroupTemplate.Items.Add(New ListItem(row("GroupName").ToString(), row("ForumGroupId").ToString()))
                        tmpGroup = row("ForumGroupId").ToString()
                    End If

                Next

            End Using
        End Sub
        Private Sub BindForumSecurity()
            Dim xDoc As New System.Xml.XmlDocument
            If String.IsNullOrEmpty(ForumConfig) Then
                xDoc.Load(Server.MapPath(Globals.ModulePath & "config/defaultgroupforums.config"))
            Else
                xDoc.LoadXml(ForumConfig)
            End If


            If Not xDoc Is Nothing Then
                Dim xRoot As System.Xml.XmlNode = xDoc.DocumentElement
                Dim xNodeList As System.Xml.XmlNodeList = xRoot.SelectSingleNode("//defaultforums/forum/security[@type='groupadmin']").ChildNodes
                Dim sb As New StringBuilder
                sb.Append("<table cellpadding=""0"" cellspacing=""0"">")
                Dim rows(15, 4) As String
                Dim i As Integer = 0
                For Each x As XmlNode In xNodeList
                    rows(i, 0) = x.Name
                    rows(i, 1) = x.Attributes("value").Value
                    i += 1
                Next
                i = 0
                xNodeList = xRoot.SelectSingleNode("//defaultforums/forum/security[@type='groupmember']").ChildNodes
                For Each x As XmlNode In xNodeList
                    rows(i, 2) = x.Attributes("value").Value
                    i += 1
                Next
                i = 0
                xNodeList = xRoot.SelectSingleNode("//defaultforums/forum/security[@type='registereduser']").ChildNodes
                For Each x As XmlNode In xNodeList
                    rows(i, 3) = x.Attributes("value").Value
                    i += 1
                Next
                i = 0
                xNodeList = xRoot.SelectSingleNode("//defaultforums/forum/security[@type='anon']").ChildNodes
                For Each x As XmlNode In xNodeList
                    rows(i, 4) = x.Attributes("value").Value
                    i += 1
                Next
                i = 0
                sb.Append("<tr id=""hd1""><td></td><td colspan=""10"" class=""afgridhd sec1"">" & LocalizeString("UserPermissions") & "</td><td colspan=""6"" class=""afgridhd sec2"">" & LocalizeString("ModeratorPermissions") & "</td></tr>")
                sb.Append("<tr id=""hd2""><td></td>")
                Dim sClass As String = String.Empty
                For i = 0 To 15
                    sClass = "afgridhdsub"
                    If i = 0 Then
                        sClass &= " colstart"
                    ElseIf i = 15 Then
                        sClass &= " colend"
                    ElseIf i = 9 Then
                        sClass &= " gridsep"

                    End If
                    sb.Append("<td class=""" & sClass & """>")
                    sb.Append(LocalizeString("SecGrid:" & rows(i, 0)))
                    sb.Append("</td>")
                Next
                sb.Append("</tr><tr id=""row1""><td class=""rowhd"">" & LocalizeString("GroupAdmin") & "</td>")
                i = 0

                For i = 0 To 15
                    sClass = "gridcheck"
                    If i <= 9 Then
                        sClass &= " sec1"
                    Else
                        sClass &= " sec2"
                    End If
                    If i = 15 Then
                        sClass &= " colend"
                    End If
                    If i = 9 Then
                        'sClass &= " gridsep"
                    End If
                    sb.Append("<td align=""center"" class=""" & sClass & """>")

                    If rows(i, 1) = "true" Then
                        sb.Append("<input type=""checkbox"" id=""ga" & rows(i, 0) & """ checked=""checked"" />")
                    Else
                        sb.Append("<input type=""checkbox"" id=""ga" & rows(i, 0) & """ />")
                    End If
                    sb.Append("</td>")
                Next
                sb.Append("</tr>")
                i = 0
                sb.Append("<tr id=""row2""><td class=""rowhd"">" & LocalizeString("GroupMember") & "</td>")
                For i = 0 To 15
                    sClass = "gridcheck"
                    If i <= 9 Then
                        sClass &= " sec1"
                    Else
                        sClass &= " sec2"
                    End If
                    If i = 15 Then
                        sClass &= " colend"
                    End If
                    If i = 9 Then
                        'sClass &= " gridsep"
                    End If
                    sb.Append("<td align=""center"" class=""" & sClass & """>")
                    If rows(i, 2) = "true" Then
                        sb.Append("<input type=""checkbox"" id=""gm" & rows(i, 0) & """ checked=""checked"" />")
                    Else
                        sb.Append("<input type=""checkbox"" id=""gm" & rows(i, 0) & """ />")
                    End If

                    sb.Append("</td>")
                Next
                sb.Append("</tr>")

                i = 0
                sb.Append("<tr id=""row3""><td class=""rowhd"">" & LocalizeString("RegisteredUser") & "</td>")
                For i = 0 To 15
                    sClass = "gridcheck"
                    If i <= 9 Then
                        sClass &= " sec1"
                    Else
                        sClass &= " sec2"
                    End If
                    If i = 15 Then
                        sClass &= " colend"
                    End If
                    If i = 9 Then
                        'sClass &= " gridsep"
                    End If
                    sb.Append("<td align=""center"" class=""" & sClass & """>")
                    If rows(i, 3) = "true" Then
                        sb.Append("<input type=""checkbox"" id=""gr" & rows(i, 0) & """ checked=""checked"" />")
                    Else
                        sb.Append("<input type=""checkbox"" id=""gr" & rows(i, 0) & """ />")
                    End If

                    sb.Append("</td>")
                Next
                sb.Append("</tr>")
                i = 0
                sb.Append("<tr id=""row4""><td class=""rowhd"">" & LocalizeString("Anon") & "</td>")
                For i = 0 To 15
                    sClass = "gridcheck"
                    If i <= 9 Then
                        sClass &= " sec1"
                    Else
                        sClass &= " sec2"
                    End If
                    If i = 15 Then
                        sClass &= " colend"
                    End If
                    If i = 9 Then
                        'sClass &= " gridsep"
                    End If
                    sb.Append("<td align=""center"" class=""" & sClass & """>")
                    If rows(i, 4) = "true" Then
                        sb.Append("<input type=""checkbox"" id=""gn" & rows(i, 0) & """ checked=""checked"" />")
                    Else
                        sb.Append("<input type=""checkbox"" id=""gn" & rows(i, 0) & """ />")
                    End If

                    sb.Append("</td>")
                Next
                sb.Append("</tr>")

                sb.Append("</table>")
                litForumSecurity.Text = sb.ToString
            End If
        End Sub
        Private Sub SaveForumSecurity(ByVal sectype As String, ByVal security() As String)
            Dim xDoc As New System.Xml.XmlDocument
            If String.IsNullOrEmpty(ForumConfig) Then
                xDoc.Load(Server.MapPath(Globals.ModulePath & "config/defaultgroupforums.config"))
            Else
                xDoc.LoadXml(ForumConfig)
            End If
            Dim xRoot As System.Xml.XmlNode = xDoc.DocumentElement
            Dim xNode As System.Xml.XmlNode = xRoot.SelectSingleNode("//defaultforums/forum/security[@type='" & sectype & "']")
            For Each s As String In security
                If Not String.IsNullOrEmpty(s) Then
                    Dim nodeName As String = s.Split(CChar("="))(0)
                    Dim nodeValue As String = s.Split(CChar("="))(1)
                    xNode.Item(nodeName).Attributes("value").Value = nodeValue
                End If
            Next
            ForumConfig = xDoc.OuterXml

        End Sub
#End Region

    End Class
End Namespace